import axios from "axios"

// 封装Axios 代码 
// Loading
// 操作提示 

const baseURL = "http://localhost:3000/";     // 基路径 

const AUTH_TOKEN = "";
// axios.defaults.baseURL = baseURL;    // 使用反向代理就不需要使用axios基路径 
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

import { Toast, Notify } from "vant"
export function ShowLoading(msg) {
    msg = msg || '加载中...'
    Toast.clear();
    Toast.loading({
        message: msg,
        forbidClick: true,
        loadingType: 'spinner',
    });
}

export function ShowSuccess(msg) {
    msg = msg || '请求成功'
    Toast.clear();
    Toast.success(msg);
}

export function ShowError(msg) {
    msg = msg || '失败'
    Notify.clear()
    Notify({
        message: msg,
        color: '#ad0000',
        background: '#ffe1e1',
    });
}
// 拦截器   Interceptors   

// 请求发送的拦截器  request
axios.interceptors.request.use(function (config) {
    // 成功
    // loading 
    ShowLoading()
    return config;
}, function (error) {
    // 失败
    ShowError("请求发送失败")
    return Promise.reject(error);
});

// 请求响应的拦截器  response
axios.interceptors.response.use(function (response) {
    // 成功
    Toast.clear()
    console.log(response.data)
    // ShowSuccess() 手机端不需要太多的提示 
    return response;
}, function (error) {
    // 失败 
    console.log(error)
    ShowError("响应失败")
    return Promise.reject(error);
});


// axios 二次封装 
export function get(url, params, headers) {
    return new Promise(function (resolve, reject) {
        axios.get(url, {
            params,  // 请求参数
            headers // 请求头 
        })
            .then(res => {
                // console.log(res)
                resolve(res.data) // res.data 当做成功回调的参数返回出去 
            })
            .catch(err => {
                reject(err)
            })
    })
}

export function post(url, body, headers) {
    return new Promise(function (resolve, reject) {
        // console.log(headers)
        axios.post(url, body, {
            headers // 请求头 
        })
            .then(res => {
                // console.log(res)
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

export function patch(url, params, headers) {
    return new Promise(function (resolve, reject) {
        axios({
            url,
            method: "patch",
            data: params,
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

export function Delete() {
    return new Promise(function (resolve, reject) {
        axios({
            url,
            method: "delete",
            data: params,
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

export {
    axios
}